package cn.imokay.lock;

import org.junit.Test;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class ThreadDemo4 {
    public static void main(String[] args) {

    }

    @Test
    public void ListTest(){

        //ArrayList 线程不安全，或导致并发修改异常
        //List<String> list = new ArrayList<>();


        /*
        这样线程安全，但是太古老，用的少

        List<String> list = Collections.synchronizedList(new ArrayList<>()) ;
        List<String> list = new Vector<>();

        */

        //推荐用法
        //线程安全
        //写时复制
        List<String> list = new CopyOnWriteArrayList<>();


        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0, 8));
                //线程不安全，打印的时候会抛出并发修改异常
                System.out.println(list);
            },String.valueOf(i)).start();
        }

    }

    @Test
    public void SetTest(){

        //HashSet 线程不安全，或导致并发修改异常
        //Set<String> list = new HashSet<>();
        Set<String> list = new CopyOnWriteArraySet<>();


        System.out.println();
        /*
        这样线程安全，但是太古老，用的少

        List<String> list = Collections.synchronizedList(new ArrayList<>()) ;
        List<String> list = new Vector<>();

        */

        //推荐用法
        //线程安全
        //写时复制
        //List<String> list = new CopyOnWriteArrayList<>();


        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0, 8));
                //线程不安全，打印的时候会抛出并发修改异常
                System.out.println(list);
            },String.valueOf(i)).start();
        }
        while(true){

        }
    }

    @Test
    public void hashMapTest(){
        //Map<String, String> map = new HashMap<>();
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            String key = String.valueOf(i);
            new Thread(()->{
                map.put(key,UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }).start();
        }

        while (true) {

        }
    }

}
